<?php
// 引入头部
require_once 'includes/header.php';

// 获取订单ID
$order_id = intval($_GET['id'] ?? 0);

if ($order_id <= 0) {
    echo '<div class="alert alert-danger">无效的订单ID</div>';
    require_once 'includes/footer.php';
    exit;
}

// 获取订单详情
$order = Database::fetch("SELECT o.*, u.name as member_name, u.phone as member_phone, c.name as cashier_name 
                        FROM orders o 
                        LEFT JOIN users u ON o.user_id = u.id 
                        LEFT JOIN users c ON o.cashier_id = c.id 
                        WHERE o.id = ?", [$order_id]);

if (!$order) {
    echo '<div class="alert alert-danger">订单不存在</div>';
    require_once 'includes/footer.php';
    exit;
}

// 获取订单明细
$order_items = Database::fetchAll("SELECT * FROM order_items WHERE order_id = ? ORDER BY id", [$order_id]);
?>

<div class="container-fluid">
    <div class="row mb-4">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">订单详情</h5>
                    <div>
                        <a href="/POS/orders.php" class="btn btn-sm btn-secondary">
                            <i class="fas fa-arrow-left"></i> 返回列表
                        </a>
                        
                        <?php if ($order['status'] !== 'cancelled' && $order['status'] !== 'completed'): ?>
                        <button class="btn btn-sm btn-success" id="complete-order-btn">
                            <i class="fas fa-check"></i> 完成订单
                        </button>
                        
                        <button class="btn btn-sm btn-danger" id="cancel-order-btn" <?php echo $order['status'] === 'cancelled' ? 'disabled' : ''; ?>>
                            <i class="fas fa-times"></i> 取消订单
                        </button>
                        <?php endif; ?>
                        
                        <button class="btn btn-sm btn-primary" id="print-order-btn">
                            <i class="fas fa-print"></i> 打印订单
                        </button>
                    </div>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            <h6>订单信息</h6>
                            <table class="table table-bordered">
                                <tr>
                                    <th width="120">订单号</th>
                                    <td><?php echo htmlspecialchars($order['order_no']); ?></td>
                                </tr>
                                <tr>
                                    <th>餐号</th>
                                    <td><?php echo htmlspecialchars($order['queue_number']); ?></td>
                                </tr>
                                <tr>
                                    <th>状态</th>
                                    <td>
                                        <?php
                                        switch ($order['status']) {
                                            case 'pending': 
                                                echo '<span class="badge badge-warning">待支付</span>'; 
                                                break;
                                            case 'paid': 
                                                echo '<span class="badge badge-primary">已支付</span>'; 
                                                break;
                                            case 'cooking': 
                                                echo '<span class="badge badge-info">制作中</span>'; 
                                                break;
                                            case 'completed': 
                                                echo '<span class="badge badge-success">已完成</span>'; 
                                                break;
                                            case 'cancelled': 
                                                echo '<span class="badge badge-danger">已取消</span>'; 
                                                break;
                                            default: 
                                                echo '<span class="badge badge-secondary">' . $order['status'] . '</span>'; 
                                                break;
                                        }
                                        ?>
                                    </td>
                                </tr>
                                <tr>
                                    <th>支付方式</th>
                                    <td>
                                        <?php
                                        switch ($order['payment_method']) {
                                            case 'cash': echo '现金'; break;
                                            case 'balance': echo '余额'; break;
                                            case 'wechat': echo '微信'; break;
                                            case 'alipay': echo '支付宝'; break;
                                            default: echo $order['payment_method']; break;
                                        }
                                        ?>
                                    </td>
                                </tr>
                                <tr>
                                    <th>下单时间</th>
                                    <td><?php echo date('Y-m-d H:i:s', strtotime($order['created_at'])); ?></td>
                                </tr>
                                <tr>
                                    <th>备注</th>
                                    <td><?php echo htmlspecialchars($order['remark'] ?? '无'); ?></td>
                                </tr>
                            </table>
                        </div>
                        
                        <div class="col-md-6">
                            <h6>金额信息</h6>
                            <table class="table table-bordered">
                                <tr>
                                    <th width="120">总金额</th>
                                    <td>¥<?php echo number_format($order['total_price'], 2); ?></td>
                                </tr>
                                <tr>
                                    <th>优惠金额</th>
                                    <td>¥<?php echo number_format($order['discount_price'], 2); ?></td>
                                </tr>
                                <tr>
                                    <th>实付金额</th>
                                    <td class="text-danger font-weight-bold">¥<?php echo number_format($order['actual_price'], 2); ?></td>
                                </tr>
                            </table>
                            
                            <h6 class="mt-4">客户信息</h6>
                            <table class="table table-bordered">
                                <tr>
                                    <th width="120">会员</th>
                                    <td><?php echo $order['user_id'] ? htmlspecialchars($order['member_name']) : '非会员'; ?></td>
                                </tr>
                                <?php if ($order['user_id']): ?>
                                <tr>
                                    <th>手机号</th>
                                    <td><?php echo htmlspecialchars($order['member_phone']); ?></td>
                                </tr>
                                <?php endif; ?>
                                <tr>
                                    <th>收银员</th>
                                    <td><?php echo htmlspecialchars($order['cashier_name']); ?></td>
                                </tr>
                            </table>
                        </div>
                    </div>
                    
                    <h6 class="mt-4">订单明细</h6>
                    <div class="table-responsive">
                        <table class="table table-bordered">
                            <thead>
                                <tr>
                                    <th>商品</th>
                                    <th>单价</th>
                                    <th>数量</th>
                                    <th>小计</th>
                                    <th>状态</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($order_items as $item): ?>
                                <tr id="item-<?php echo $item['id']; ?>">
                                    <td><?php echo htmlspecialchars($item['product_name']); ?></td>
                                    <td>¥<?php echo number_format($item['price'], 2); ?></td>
                                    <td><?php echo $item['quantity']; ?></td>
                                    <td>¥<?php echo number_format($item['subtotal'], 2); ?></td>
                                    <td class="item-status">
                                        <?php
                                        switch ($item['status']) {
                                            case 'pending': 
                                                echo '<span class="badge badge-warning">待处理</span>'; 
                                                break;
                                            case 'cooking': 
                                                echo '<span class="badge badge-info">制作中</span>'; 
                                                break;
                                            case 'completed': 
                                                echo '<span class="badge badge-success">已完成</span>'; 
                                                break;
                                            default: 
                                                echo '<span class="badge badge-secondary">' . $item['status'] . '</span>'; 
                                                break;
                                        }
                                        ?>
                                    </td>
                                    <td>
                                        <?php if ($order['status'] !== 'cancelled' && $order['status'] !== 'completed' && $item['status'] !== 'completed'): ?>
                                        <button class="btn btn-sm btn-success complete-item-btn" data-id="<?php echo $item['id']; ?>">
                                            <i class="fas fa-check"></i> 完成
                                        </button>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // 完成订单按钮
    const completeOrderBtn = document.getElementById('complete-order-btn');
    if (completeOrderBtn) {
        completeOrderBtn.addEventListener('click', function() {
            if (confirm('确定要将订单标记为已完成吗？')) {
                updateOrderStatus('completed');
            }
        });
    }
    
    // 取消订单按钮
    const cancelOrderBtn = document.getElementById('cancel-order-btn');
    if (cancelOrderBtn) {
        cancelOrderBtn.addEventListener('click', function() {
            if (confirm('确定要取消此订单吗？这将退还任何已支付的金额。')) {
                updateOrderStatus('cancelled');
            }
        });
    }
    
    // 更新订单状态
    function updateOrderStatus(status) {
        fetch('/api/orders.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: JSON.stringify({
                action: 'update_status',
                order_id: <?php echo $order_id; ?>,
                status: status
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showAlert('订单状态已更新', 'success');
                setTimeout(() => {
                    window.location.reload();
                }, 1000);
            } else {
                showAlert(data.message || '更新失败', 'danger');
            }
        })
        .catch(error => {
            showAlert('请求发生错误: ' + error, 'danger');
        });
    }
    
    // 完成订单项按钮
    const completeItemBtns = document.querySelectorAll('.complete-item-btn');
    completeItemBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            const itemId = this.dataset.id;
            if (confirm('确定要将此商品标记为已完成吗？')) {
                updateItemStatus(itemId, 'completed');
            }
        });
    });
    
    // 更新订单项状态
    function updateItemStatus(itemId, status) {
        fetch('/api/orders.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: JSON.stringify({
                action: 'update_item_status',
                item_id: itemId,
                status: status
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showAlert('商品状态已更新', 'success');
                
                // 更新UI
                const itemRow = document.getElementById('item-' + itemId);
                if (itemRow) {
                    const statusCell = itemRow.querySelector('.item-status');
                    if (statusCell) {
                        statusCell.innerHTML = '<span class="badge badge-success">已完成</span>';
                    }
                    
                    // 隐藏按钮
                    const btnCell = itemRow.querySelector('.complete-item-btn');
                    if (btnCell) {
                        btnCell.style.display = 'none';
                    }
                }
                
                // 如果订单状态也变化了，刷新页面
                if (data.order.status !== '<?php echo $order['status']; ?>') {
                    setTimeout(() => {
                        window.location.reload();
                    }, 1000);
                }
            } else {
                showAlert(data.message || '更新失败', 'danger');
            }
        })
        .catch(error => {
            showAlert('请求发生错误: ' + error, 'danger');
        });
    }
    
    // 打印订单按钮
    const printOrderBtn = document.getElementById('print-order-btn');
    if (printOrderBtn) {
        printOrderBtn.addEventListener('click', function() {
            printOrder();
        });
    }
    
    // 打印订单
    function printOrder() {
        const printWindow = window.open('', '_blank');
        
        // 构建打印内容
        let printContent = `
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <title>订单 #<?php echo $order['order_no']; ?></title>
            <style>
                body {
                    font-family: 'Microsoft YaHei', Arial, sans-serif;
                    font-size: 12px;
                    margin: 0;
                    padding: 10px;
                    width: 80mm;
                }
                .header {
                    text-align: center;
                    margin-bottom: 10px;
                    border-bottom: 1px dashed #000;
                    padding-bottom: 5px;
                }
                .title {
                    font-size: 14px;
                    font-weight: bold;
                }
                .info {
                    margin-bottom: 10px;
                }
                .info div {
                    margin-bottom: 5px;
                }
                table {
                    width: 100%;
                    border-collapse: collapse;
                    margin-bottom: 10px;
                }
                table th, table td {
                    text-align: left;
                    padding: 5px 2px;
                }
                table th {
                    border-bottom: 1px solid #000;
                }
                .total {
                    text-align: right;
                    margin-top: 10px;
                    padding-top: 5px;
                    border-top: 1px dashed #000;
                }
                .footer {
                    text-align: center;
                    margin-top: 20px;
                    border-top: 1px dashed #000;
                    padding-top: 5px;
                }
                @media print {
                    body {
                        width: 100%;
                    }
                }
            </style>
        </head>
        <body>
            <div class="header">
                <div class="title">餐饮收银系统</div>
                <div>订单小票</div>
            </div>
            
            <div class="info">
                <div>订单号: <?php echo $order['order_no']; ?></div>
                <div>餐号: <?php echo $order['queue_number']; ?></div>
                <div>时间: <?php echo date('Y-m-d H:i:s', strtotime($order['created_at'])); ?></div>
                <?php if ($order['user_id']): ?>
                <div>会员: <?php echo $order['member_name']; ?></div>
                <?php endif; ?>
            </div>
            
            <table>
                <tr>
                    <th>商品</th>
                    <th style="text-align:right">单价</th>
                    <th style="text-align:right">数量</th>
                    <th style="text-align:right">小计</th>
                </tr>
                <?php foreach ($order_items as $item): ?>
                <tr>
                    <td><?php echo $item['product_name']; ?></td>
                    <td style="text-align:right">¥<?php echo number_format($item['price'], 2); ?></td>
                    <td style="text-align:right"><?php echo $item['quantity']; ?></td>
                    <td style="text-align:right">¥<?php echo number_format($item['subtotal'], 2); ?></td>
                </tr>
                <?php endforeach; ?>
            </table>
            
            <div class="total">
                <div>总计: ¥<?php echo number_format($order['total_price'], 2); ?></div>
                <?php if ($order['discount_price'] > 0): ?>
                <div>优惠: ¥<?php echo number_format($order['discount_price'], 2); ?></div>
                <?php endif; ?>
                <div style="font-weight:bold">实付: ¥<?php echo number_format($order['actual_price'], 2); ?></div>
                <div>支付方式: 
                    <?php
                    switch ($order['payment_method']) {
                        case 'cash': echo '现金'; break;
                        case 'balance': echo '余额'; break;
                        case 'wechat': echo '微信'; break;
                        case 'alipay': echo '支付宝'; break;
                        default: echo $order['payment_method']; break;
                    }
                    ?>
                </div>
            </div>
            
            <?php if (!empty($order['remark'])): ?>
            <div>
                <div>备注: <?php echo $order['remark']; ?></div>
            </div>
            <?php endif; ?>
            
            <div class="footer">
                <div>感谢您的惠顾，欢迎再次光临！</div>
            </div>
        </body>
        </html>
        `;
        
        printWindow.document.write(printContent);
        printWindow.document.close();
        printWindow.onload = function() {
            printWindow.print();
            printWindow.onafterprint = function() {
                printWindow.close();
            };
        };
    }
});
</script>

<?php
// 引入页脚
require_once 'includes/footer.php';
?> 